package com.xju.subjectsystem.interceptors;

import com.xju.subjectsystem.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * -*- coding:utf-8 -*-
 *
 * @projectName: Subjectsystem
 * @package: com.xju.subjectsystem.interceptors
 * @className: TokenInterceptors
 * @author: Eiard
 * @description: DONE : 令牌校验拦截器
 * @date: 2024-12-09 13:55
 */
@Slf4j
@Component
public class TokenInterceptors implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        String token = request.getHeader("token");

        if (token == null || token.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        try {
            JwtUtil.parseToken(token);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        log.info("TokenInterceptors: 令牌校验成功");

        return true;
    }
}
